import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import DPlayer from 'dplayer';
import './style/video-model.less';

const Hls = require('hls.js');

const PreviewVideo = forwardRef((props, ref) => {
  let dp = useRef();

  const [modal2Open, setModal2Open] = useState(false);
  const [fileId, setFileId] = useState('');

  const showPreview = (fileId) => {
    setFileId(fileId);
    setModal2Open(true);
  };

  const hideModal = () => {
    setModal2Open(false);
  };

  const clickModal = (e) => {
    if (e.target.dataset.tagName === 'parentBox') {
      hideModal();
    }
  };

  useEffect(() => {
    if (modal2Open) {
      console.log(fileId, 'videovideovideo');
      dp.current = new DPlayer({
        container: document.getElementById('video'), // 注意：这里一定要写div的dom
        lang: 'zh-cn',
        video: {
          url: `/api/pan/preview/${fileId}`, // 这里填写.m3u8视频连接
          type: 'customHls',
          customType: {
            customHls: function (video) {
              const hls = new Hls();
              hls.loadSource(video.src);
              hls.attachMedia(video);
            },
          },
        },
      });
      dp.current.play();
    }
  }, [modal2Open]);

  useImperativeHandle(ref, () => {
    return {
      showPreview,
    };
  });

  return (
    <>
      {modal2Open && (
        <div className={'video-box'} data-tag-name={'parentBox'} onClick={clickModal}>
          <div id="video"></div>
          <button className="ant-image-preview-close" onClick={hideModal}>
            <span role="img" aria-label="close" className="anticon anticon-close">
              <svg
                fill-rule="evenodd"
                viewBox="64 64 896 896"
                focusable="false"
                data-icon="close"
                width="1em"
                height="1em"
                fill="currentColor"
                aria-hidden="true"
              >
                <path d="M799.86 166.31c.02 0 .04.02.08.06l57.69 57.7c.04.03.05.05.06.08a.12.12 0 010 .06c0 .03-.02.05-.06.09L569.93 512l287.7 287.7c.04.04.05.06.06.09a.12.12 0 010 .07c0 .02-.02.04-.06.08l-57.7 57.69c-.03.04-.05.05-.07.06a.12.12 0 01-.07 0c-.03 0-.05-.02-.09-.06L512 569.93l-287.7 287.7c-.04.04-.06.05-.09.06a.12.12 0 01-.07 0c-.02 0-.04-.02-.08-.06l-57.69-57.7c-.04-.03-.05-.05-.06-.07a.12.12 0 010-.07c0-.03.02-.05.06-.09L454.07 512l-287.7-287.7c-.04-.04-.05-.06-.06-.09a.12.12 0 010-.07c0-.02.02-.04.06-.08l57.7-57.69c.03-.04.05-.05.07-.06a.12.12 0 01.07 0c.03 0 .05.02.09.06L512 454.07l287.7-287.7c.04-.04.06-.05.09-.06a.12.12 0 01.07 0z"></path>
              </svg>
            </span>
          </button>
        </div>
      )}
    </>
  );
});

export default PreviewVideo;
